﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace Sinuo
{
    public class URLModule : IHttpModule
    {
        public URLModule()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;
            HttpResponse response = context.Response;
            HttpRequest request = context.Request;

            String url = request.RawUrl;
            String query = "";
            if (url.Contains("?"))
            {
                query = url.Substring(url.IndexOf("?") + 1);
                url = url.Remove(url.IndexOf("?"));
            }
            if (url.EndsWith(".jpg") || url.EndsWith(".gif") || url.EndsWith(".png") || url.EndsWith(".rpt")) { }
            else if (!url.Contains(".aspx"))
            {
                query = "";
                foreach (string k in HttpContext.Current.Request.QueryString.Keys)
                {
                    if (k != "taguid")
                        query += k + "=" + HttpContext.Current.Request.QueryString[k] + "&";
                }

                if (query.EndsWith("&")) query = query.Remove(query.Length - 1);

                Regex reg = new Regex("^/Touch/(\\w+)([/]?)$", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                Regex Consortium = new Regex("^/Consortium/(\\w+)([/]?)$", RegexOptions.Singleline | RegexOptions.IgnoreCase);

                if (reg.IsMatch(url))
                {
                    Match m = reg.Match(url);
                    context.RewritePath("/Touch.aspx", string.Empty, query + "&taguid=" + m.Groups[1].Value);


                }

                if (Consortium.IsMatch(url))
                {
                    Match m = Consortium.Match(url);
                    context.RewritePath("/Touch.aspx", string.Empty, query + "&taguid=" + m.Groups[1].Value);
                }
            }
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;
            HttpResponse response = context.Response;
        }

        public void Dispose() { }
    }
}